package com.hjc.controller;

import com.hjc.dto.AssignRoleDto;
import com.hjc.entity.CurrentUser;
import com.hjc.entity.Result;
import com.hjc.entity.User;
import com.hjc.page.Page;
import com.hjc.service.RoleService;
import com.hjc.service.UserService;
import com.hjc.utils.TokenUtils;
import com.hjc.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private TokenUtils tokenUtils;

    @RequestMapping("/user-list")
    public Result UserList(Page page, User user) {
        page = userService.queryUserByPage(page, user);
        return Result.ok(page);
    }

    @RequestMapping("/addUser")
    public Result addUser(@RequestBody User user, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        for (int ii = 0;ii < 10; ii++) {
            System.out.println("token:" + token);
        }
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int createBy = currentUser.getUserId();
        user.setCreateBy(createBy);
        return userService.saveUser(user);
    }

    @RequestMapping("/updateState")
    public Result updateUserState(@RequestBody User user) {
        return userService.setUserState(user);
    }


    @RequestMapping("/user-role-list/{userId}")
    public Result userRoleList(@PathVariable Integer userId) {
        return userService.queryRoleByUserId(userId);
    }

    @RequestMapping("/assignRole")
    public Result assignRole(@RequestBody AssignRoleDto assignRoleDto) {
        roleService.assignRole(assignRoleDto);
        return Result.ok("分配角色成功！");
    }

    @RequestMapping("/deleteUser/{userId}")
    public Result removeUserByUserId(@PathVariable Integer userId) {
        return userService.removeUserByUserId(Arrays.asList(userId));
    }

    @RequestMapping("/deleteUserList")
    public Result removeUserByUserIds(@RequestBody List<Integer> userIdList) {
        return userService.removeUserByUserId(userIdList);
    }

    @RequestMapping("/updateUser")
    public Result setUserNameByUserId(@RequestBody User user,@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token) {
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        int updateBy = currentUser.getUserId();
        user.setUpdateBy(updateBy);
        return userService.setUserNameByUserId(user);
    }

    @RequestMapping("/updatePwd/{userId}")
    public Result setPwdByUserId(@PathVariable Integer userId) {
        return userService.setPwdByUserId(userId);
    }

}
